<template>
  <div style="flex: 90%; margin-top: 20px; margin-left: 20px">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="最高价">
        <el-input
          v-model="formInline.price"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="计算天数">
        <el-input
          v-model="formInline.dayCount"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="偏移天数">
        <el-input v-model="formInline.difDays" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="增长百分比(%)">
        <el-input v-model="formInline.upSum" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="红次数">
        <el-input v-model="formInline.upCount" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onFucus">关注列表</el-button>
      </el-form-item>
    </el-form>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="选日期">
        <el-date-picker
                v-model="formInline.dateTime"
                type="date"
                placeholder="Pick a day"
                size="large"
                @change="handleDateChange"
            />
      </el-form-item>
      <el-form-item label="涨跌幅(%)">
        <el-input v-model="formInline.upDown" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearchByDate">查询</el-button>
      </el-form-item>
    </el-form>
    
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="股票代码">
        <el-input
          v-model="formInline.code"
          style="width: 240px"
          placeholder="input stock code"
          @update:model-value="onInputChange"
      /></el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      ref="tableRef"
      row-key="code"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="code" label="代码" width="180" />
      <el-table-column prop="currentPrice" label="价格" width="180"/>
      <el-table-column prop="focus" label="操作" width="300" >
      <template #default="scope">
        <el-button  @click="handleEdit(scope.$index, scope.row)" 
        :type="['','success','primary','danger'][scope.row.focus]"  plain>
          {{ ['未关注','已关注','观察中','Vip关注'][scope.row.focus]}}
        </el-button>
        <el-button  @click="handleCopy(scope.$index, scope.row)" class="btn-copy" width="180" plain>
          复制
        </el-button>
        <el-button  @click="handleOpen(scope.row.code)" class="btn-copy" width="180" plain>
          开单
        </el-button>
      </template>
    </el-table-column>
    </el-table>

    <div style="display: flex;margin-top: 12px;" v-show="isVisible">
      <p class="label">风格和炒作逻辑</p>
      <el-select v-model="value_type" placeholder="Select" size="large" class="select" style="width:20%;margin-left: 20px;margin-right: 20px;margin-top: 6px;">
          <el-option v-for="item in options_type" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-input 
        v-model="logic"
        style="width: 360px;margin-top: 6px;"
        :rows="3"
        type="textarea"
        placeholder="Please input"
      />
      <el-button type="primary" style="margin-left: 10px;margin-top: 10px" @click="onSubmit_AddOrder">确认</el-button>
      <el-button type="primary" style="margin-left: 10px;margin-top: 10px" @click="clickCancle">取消</el-button>
    </div>
  </div>
</template>
  
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type { TableColumnCtx, TableInstance } from "element-plus";
import { reactive } from "vue";
import axios from "axios";
import { countdownEmits, ElMessage } from "element-plus";
import ClipboardJS from 'clipboard';
import { useStore } from 'vuex';

const value_type ='短线风格'
const options_type = [
                { value: '市场情绪龙' },
                { value: '市场趋势龙' },

                { value: '板块情绪龙' },
                { value: '板块趋势龙' },
                { value: '板块领涨龙' },

                { value: '低吸回调老龙' },
                { value: '发布会预期龙' },
                { value: '避险龙' },

            ]

var logic = "sdfasd"

const formInline = reactive({
  dayCount: "",
  upSum: "0",
  upCount: "0",
  difDays: "0",
  code: "",
  price: "100",

  upDown:0.0,
  dateTime: '',
});

var isVisible = ref(true)
const clickCancle = () => {
  alert("取消")  
  isVisible.value = false
}
const handleOpen = (pcode) => {
  isVisible.value = true
  formInline.code = pcode
}

const onSubmit_AddOrder = () => {
  axios.post("api/plat/stockOrder/add", {
    code:formInline.code
  }).then((response) => {
    console.log(response);
    if (response.data.status == 200) {
        ElMessage({
          message: "下单成功",
          type: "warning",
        });
      } else {
        ElMessage({
          message: "下单失败",
          type: "warning",
        });
      }
  })
}


const onSubmit = () => {
  if (formInline.dayCount == "") {
    ElMessage({
      message: "天数必须大于0",
      type: "warning",
    });
    return;
  }
  loading.value = true;
  console.log(formInline);
  console.log("submit!");
  axios
    .get(
      "api/plat/stock/getStockList?dayCount=" +
        formInline.dayCount +
        "&upSum=" +
        formInline.upSum +
        "&upCount=" +
        formInline.upCount +
        "&difDays=" +
        formInline.difDays +
        "&price=" + formInline.price
    )
    .then((response) => {
      loading.value = false;
      if (response.data.status == 300) {
        ElMessage({
          message: "数据量较大，只截取前100条",
          type: "warning",
        });
      }
      tableData.value = response.data.data;
      console.log("数量" + response.data.data.length);
    })
    .catch((error) => {
      loading.value = false;
      console.error("Error fetching data:", error);
    });
};

const onFucus = () => {
  console.log(formInline);
  console.log("submit!");
  axios
    .get("api/plat/stock/getStockFocusList?focus=0")
    .then((response) => {
      tableData.value = response.data.data;
      console.log(tableData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onSearh = (str: string, type: number) => {
  console.log("submit!");
  const encodedName = encodeURIComponent(str);
  const api = "api/plat/stock/getStockListByCode?type=" + type + (type === 1 ?  "&code=" + str : "&name=" + encodedName);
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableData.value = response.data.data;
      console.log(tableData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onSearchByDate = () => {
  console.log("submit!");
  loading.value = true;
  const api = "api/plat/stock/getStockListByDateUpDown?date=" + formInline.dateTime + "&upDown=" + formInline.upDown;
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      loading.value = false;
      tableData.value = response.data.data;
      console.log(tableData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onUpdateFoucus = (id: number, focus: number) => {
  console.log("submit!");
  axios
    .get("api/plat/stockName/updateFocus?id=" + id + "&focus=" + focus)
    .then((response) => {
      // console.log(response.status);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

interface StockName {
  id: number;
  name: string;
  code: string;
  focus: number;
  riskLevel: number;
  marketType: string;
  stockType: string;
  currentPrice: number;
  isEnable: number;
  isInitDayData: number;
  dayCount: number;
  createTime: string;
  updateTime: string;
}

const onInputChange = (newValue, oldValue) => {
  console.log("Input changed:", newValue);
  const containsChinese = /[\u4e00-\u9fa5]/.test(newValue);
  if (containsChinese) {
    onSearh(newValue, 2);
  } else if (newValue.length == 6) {
    onSearh(newValue, 1);
  }
};


const handleDateChange = (val) => {
    console.log('选择了新的日期/时间:', val);
    const date = new Date(val)
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要加1
    const day = ('0' + date.getDate()).slice(-2);
    const dayTime = `${year}-${month}-${day}`;
    console.log('选择了新的日期/时间:', dayTime);
    formInline.dateTime = dayTime;
};

const loading = ref(false);
const tableRef = ref<TableInstance>();

const tableData = ref([]);

const store = useStore();
const handleEdit = (index: number, row: StockName) => {
  console.log(index, row)
  if (row.focus == 0) {
    row.focus = 1;
  } else if (row.focus == 1) {
    store.dispatch('changeStockCode', row.code);
    store.dispatch('changeStockName', row.name);
    console.log("股票代码" + store.state.stockCode);
    row.focus = 2;
  } else if (row.focus == 2) {
    row.focus = 3;
  }else if (row.focus == 3) {
    row.focus = 0;
  }
  onUpdateFoucus(row.id, row.focus);
}




var code = ''
onMounted(() => {
      const clipboard = new ClipboardJS('.btn-copy', {
        text: () => code
      });

      clipboard.on('success', (e) => {
        console.log('Text copied to clipboard');
        e.clearSelection();
      });

      clipboard.on('error', (e) => {
        console.error('Failed to copy text: ', e);
      });
    });

const  handleCopy = (index: number, row: StockName) => {
  console.log(index, row)
  code = row.code
}
</script>
  



<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>